package com.example.hszpad.fragment;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.hszpad.R;
import com.example.hszpad.adapter.BaseRecyclerAdapter;
import com.example.hszpad.adapter.SmartViewHolder;
import com.example.hszpad.bean.HistoryDataBean;
import com.example.hszpad.bean.PointDataBean;
import com.example.hszpad.util.DateUtil;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.ViewPortHandler;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 实时数据界面
 */
public class HSZViewFragmentReal extends Fragment implements OnChartValueSelectedListener {
    private LineChart chart;

    protected Typeface tfRegular;
    protected Typeface tfLight;


    private LineDataSet set1;
    private LineDataSet set2;
    private LineDataSet set3;
    private LineDataSet set4;
    private LineDataSet set5;
    private LineDataSet set6;

    ArrayList<Entry> values1 = new ArrayList<>();
    ArrayList<Entry> values2 = new ArrayList<>();
    ArrayList<Entry> values3 = new ArrayList<>();
    ArrayList<Entry> values4 = new ArrayList<>();
    ArrayList<Entry> values5 = new ArrayList<>();
    ArrayList<Entry> values6 = new ArrayList<>();

    private List<String> tipList = new ArrayList<>();
    private Random random = new Random();
    private Handler handler = new Handler();
    private Runnable task = new Runnable() {
        @Override
        public void run() {
            refreshData(8);
            handler.postDelayed(task, 1000);
        }
    };

    private TextView tv_01;
    private TextView tv_02;
    private TextView tv_03;
    private TextView tv_04;
    private TextView tv_05;
    private TextView tv_06;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_hszview_fragment_real, container, false);
        tfRegular = Typeface.createFromAsset(getActivity().getAssets(), "OpenSans-Regular.ttf");
        tfLight = Typeface.createFromAsset(getActivity().getAssets(), "OpenSans-Light.ttf");
        tv_01 = view.findViewById(R.id.tv_01);
        tv_02 = view.findViewById(R.id.tv_02);
        tv_03 = view.findViewById(R.id.tv_03);
        tv_04 = view.findViewById(R.id.tv_04);
        tv_05 = view.findViewById(R.id.tv_05);
        tv_06 = view.findViewById(R.id.tv_06);
        chart = view.findViewById(R.id.chart1);
        chart.setOnChartValueSelectedListener(this);

        // no description text
        chart.getDescription().setEnabled(false);

        // enable touch gestures
        chart.setTouchEnabled(true);

        chart.setDragDecelerationFrictionCoef(0.9f);

        // enable scaling and dragging
        chart.setDragEnabled(true);
        chart.setScaleEnabled(true);
        chart.setDrawGridBackground(false);
        chart.setHighlightPerDragEnabled(true);

        // if disabled, scaling can be done on x- and y-axis separately
        chart.setPinchZoom(true);

        // set an alternative background color
        chart.setBackgroundColor(Color.WHITE);
        chart.setGridBackgroundColor(Color.GRAY);

        chart.animateX(1500);

        // get the legend (only possible after setting data)
        Legend l = chart.getLegend();

        // modify the legend ...
        l.setForm(Legend.LegendForm.LINE);
        l.setTypeface(tfLight);
        l.setTextSize(12f);
        l.setTextColor(getContext().getResources().getColor(R.color.colorPrimary));
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);

        XAxis xAxis = chart.getXAxis();
        xAxis.setTypeface(tfLight);
        xAxis.setTextSize(12f);
        xAxis.setTextColor(getContext().getResources().getColor(R.color.colorPrimary));
        xAxis.setDrawGridLines(false);
        xAxis.setDrawAxisLine(false);
        xAxis.setAxisMaximum(8);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                int index = (int) value;
                if (index >= 0 && index < tipList.size()) {
                    return tipList.get(index);
                } else {
                    return "";
                }
            }
        });

        YAxis leftAxis = chart.getAxisLeft();
        leftAxis.setTypeface(tfLight);
        leftAxis.setTextColor(ColorTemplate.getHoloBlue());
        leftAxis.setAxisMaximum(200f);
        leftAxis.setTextSize(12);
        leftAxis.setAxisMinimum(0f);
        leftAxis.setDrawGridLines(true);
        leftAxis.setGranularityEnabled(true);

        YAxis rightAxis = chart.getAxisRight();
        rightAxis.setTypeface(tfLight);
        rightAxis.setTextColor(Color.RED);
        rightAxis.setTextSize(12);
        rightAxis.setAxisMaximum(100);
        rightAxis.setAxisMinimum(-200);
        rightAxis.setDrawGridLines(false);
        rightAxis.setDrawZeroLine(false);
        rightAxis.setGranularityEnabled(false);

        set1 = new LineDataSet(values1, getActivity().getResources().getString(R.string.string_tip01));
        set1.setAxisDependency(YAxis.AxisDependency.LEFT);
        set1.setColor(getContext().getResources().getColor(R.color.color_chart_01));
        set1.setCircleColor(getContext().getResources().getColor(R.color.colorPrimary));
        set1.setLineWidth(2f);
        set1.setValueTextColor(getContext().getResources().getColor(R.color.colorPrimary));
        set1.setCircleRadius(3f);
        set1.setFillAlpha(65);
        set1.setValueFormatter(new IValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                return String.format("%.02fMpa", value);
            }
        });
        set1.setFillColor(getContext().getResources().getColor(R.color.color_chart_01));
        set1.setHighLightColor(Color.rgb(244, 117, 117));
        set1.setDrawCircleHole(false);

        set2 = new LineDataSet(values2, getActivity().getResources().getString(R.string.string_tip02));
        set2.setAxisDependency(YAxis.AxisDependency.LEFT);
        set2.setColor(getContext().getResources().getColor(R.color.color_chart_02));
        set2.setCircleColor(getContext().getResources().getColor(R.color.colorPrimary));
        set2.setLineWidth(2f);
        set2.setValueTextColor(getContext().getResources().getColor(R.color.colorPrimary));
        set2.setCircleRadius(3f);
        set2.setFillAlpha(65);
        set2.setFillColor(getContext().getResources().getColor(R.color.color_chart_02));
        set2.setHighLightColor(Color.rgb(244, 117, 117));
        set2.setDrawCircleHole(false);
        set2.setValueFormatter(new IValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                return String.format("%.01f℃", value);
            }
        });

        set3 = new LineDataSet(values3, getActivity().getResources().getString(R.string.string_tip03));
        set3.setAxisDependency(YAxis.AxisDependency.LEFT);
        set3.setColor(getContext().getResources().getColor(R.color.color_chart_03));
        set3.setCircleColor(getContext().getResources().getColor(R.color.colorPrimary));
        set3.setLineWidth(2f);
        set3.setValueTextColor(getContext().getResources().getColor(R.color.colorPrimary));
        set3.setCircleRadius(3f);
        set3.setFillAlpha(65);
        set3.setFillColor(getContext().getResources().getColor(R.color.color_chart_03));
        set3.setHighLightColor(Color.rgb(244, 117, 117));
        set3.setDrawCircleHole(false);
        set3.setValueFormatter(new IValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                return String.format("%.01f℃", value);
            }
        });

        set4 = new LineDataSet(values4, getActivity().getResources().getString(R.string.string_tip04));
        set4.setAxisDependency(YAxis.AxisDependency.LEFT);
        set4.setColor(getContext().getResources().getColor(R.color.color_chart_04));
        set4.setValueTextColor(getContext().getResources().getColor(R.color.colorPrimary));
        set4.setCircleColor(getContext().getResources().getColor(R.color.colorPrimary));
        set4.setLineWidth(2f);
        set4.setCircleRadius(3f);
        set4.setFillAlpha(65);
        set4.setValueFormatter(new IValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                return String.format("%.02fMpa", value);
            }
        });
        set4.setFillColor(getContext().getResources().getColor(R.color.color_chart_04));
        set4.setHighLightColor(Color.rgb(244, 117, 117));
        set4.setDrawCircleHole(false);

        set5 = new LineDataSet(values5, getActivity().getResources().getString(R.string.string_tip05));
        set5.setAxisDependency(YAxis.AxisDependency.LEFT);
        set5.setColor(getContext().getResources().getColor(R.color.color_chart_05));
        set5.setValueTextColor(getContext().getResources().getColor(R.color.colorPrimary));
        set5.setCircleColor(getContext().getResources().getColor(R.color.colorPrimary));
        set5.setLineWidth(2f);
        set5.setCircleRadius(3f);
        set5.setFillAlpha(65);
        set5.setFillColor(getContext().getResources().getColor(R.color.color_chart_05));
        set5.setHighLightColor(Color.rgb(244, 117, 117));
        set5.setDrawCircleHole(false);
        set5.setValueFormatter(new IValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                return String.format("%.01f℃", value);
            }
        });

        set6 = new LineDataSet(values6, getActivity().getResources().getString(R.string.string_tip06));
        set6.setAxisDependency(YAxis.AxisDependency.LEFT);
        set6.setColor(getContext().getResources().getColor(R.color.color_chart_06));
        set6.setValueTextColor(getContext().getResources().getColor(R.color.colorPrimary));
        set6.setCircleColor(getContext().getResources().getColor(R.color.colorPrimary));
        set6.setLineWidth(2f);
        set6.setCircleRadius(3f);
        set6.setFillAlpha(65);
        set6.setValueFormatter(new IValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                return String.format("%.01f℃", value);
            }
        });
        set6.setFillColor(getContext().getResources().getColor(R.color.color_chart_06));
        set6.setHighLightColor(Color.rgb(244, 117, 117));
        set6.setDrawCircleHole(false);
        // create a data object with the data sets
        LineData data = new LineData(set1, set2, set3, set4, set5, set6);
        data.setValueTextColor(getContext().getResources().getColor(R.color.colorPrimary));
        data.setValueTextSize(12f);
        // set data
        chart.setData(data);
//        setData(10, 100);
        handler.postDelayed(task, 1000);
        return view;
    }


    private void refreshData(int count) {
        while (values1.size() > count) {
            values1.remove(0);
        }
        while (values2.size() > count) {
            values2.remove(0);
        }
        while (values3.size() > count) {
            values3.remove(0);
        }
        while (values4.size() > count) {
            values4.remove(0);
        }
        while (values5.size() > count) {
            values5.remove(0);
        }
        while (values6.size() > count) {
            values6.remove(0);
        }

        while (tipList.size() > count) {
            tipList.remove(0);
        }
        tipList.add(DateUtil.getShortNow());
        float val1 = (50 + random.nextInt(70)) / 100.0f;
        float val2 = (700 + random.nextInt(300)) / 10.f;
        float val3 = (250 + random.nextInt(70)) / 10.f;
        float val4 = (180 + random.nextInt(70)) / 100.f;
        float val5 = (280 + random.nextInt(70)) / 10.f;
        float val6 = (850 + random.nextInt(140)) / 10.f;
        tv_01.setText(String.format("%.02fMpa", val1));
        tv_02.setText(String.format("%.01f℃", val2));
        tv_03.setText(String.format("%.01f℃", val3));
        tv_04.setText(String.format("%.02fMpa", val4));
        tv_05.setText(String.format("%.01f℃", val5));
        tv_06.setText(String.format("%.01f℃", val6));
        values1.add(new Entry(values1.size(), val1));
        values2.add(new Entry(values2.size(), val2));
        values3.add(new Entry(values3.size(), val3));
        values4.add(new Entry(values4.size(), val4));
        values5.add(new Entry(values5.size(), val5));
        values6.add(new Entry(values6.size(), val6));
        for (int i = 0; i < values1.size(); i++) {
            values1.get(i).setX(i);
        }
        for (int i = 0; i < values2.size(); i++) {
            values2.get(i).setX(i);
        }
        for (int i = 0; i < values3.size(); i++) {
            values3.get(i).setX(i);
        }
        for (int i = 0; i < values4.size(); i++) {
            values4.get(i).setX(i);
        }
        for (int i = 0; i < values5.size(); i++) {
            values5.get(i).setX(i);
        }
        for (int i = 0; i < values6.size(); i++) {
            values6.get(i).setX(i);
        }
        set1.setValues(values1);
        set2.setValues(values2);
        set3.setValues(values3);
        set4.setValues(values4);
        set5.setValues(values5);
        set6.setValues(values6);
        chart.getData().notifyDataChanged();
        chart.notifyDataSetChanged();
        chart.invalidate();
    }

    private void setData(int count, float range) {

        ArrayList<Entry> values1 = new ArrayList<>();

        for (int i = 0; i < count; i++) {
            float val = (float) (Math.random() * (range / 2f)) + 50;
            values1.add(new Entry(i, val));
        }

        ArrayList<Entry> values2 = new ArrayList<>();

        for (int i = 0; i < count; i++) {
            float val = (float) (Math.random() * range) + 450;
            values2.add(new Entry(i, val));
        }

        ArrayList<Entry> values3 = new ArrayList<>();

        for (int i = 0; i < count; i++) {
            float val = (float) (Math.random() * range) + 500;
            values3.add(new Entry(i, val));
        }

        LineDataSet set1, set2, set3, set4, set5;

        if (chart.getData() != null &&
                chart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) chart.getData().getDataSetByIndex(0);
            set2 = (LineDataSet) chart.getData().getDataSetByIndex(1);
            set3 = (LineDataSet) chart.getData().getDataSetByIndex(2);
            set1.setValues(values1);
            set2.setValues(values2);
            set3.setValues(values3);
            chart.getData().notifyDataChanged();
            chart.notifyDataSetChanged();
        } else {
            // create a dataset and give it a type
            set1 = new LineDataSet(values1, "抽水泵状态");

            set1.setAxisDependency(YAxis.AxisDependency.LEFT);
            set1.setColor(ColorTemplate.getHoloBlue());
            set1.setCircleColor(Color.WHITE);
            set1.setLineWidth(2f);
            set1.setCircleRadius(3f);
            set1.setFillAlpha(65);
            set1.setFillColor(ColorTemplate.getHoloBlue());
            set1.setHighLightColor(Color.rgb(244, 117, 117));
            set1.setDrawCircleHole(false);
//            set1.setFillFormatter(new MyFillFormatter(0f));
            //set1.setDrawHorizontalHighlightIndicator(false);
            //set1.setVisible(false);
            //set1.setCircleHoleColor(Color.WHITE);

            // create a dataset and give it a type
            set2 = new LineDataSet(values2, "DataSet 2");
            set2.setAxisDependency(YAxis.AxisDependency.RIGHT);
            set2.setColor(Color.RED);
            set2.setCircleColor(Color.WHITE);
            set2.setLineWidth(2f);
            set2.setCircleRadius(3f);
            set2.setFillAlpha(65);
            set2.setFillColor(Color.RED);
            set2.setDrawCircleHole(false);
            set2.setHighLightColor(Color.rgb(244, 117, 117));
            //set2.setFillFormatter(new MyFillFormatter(900f));

            set3 = new LineDataSet(values3, "DataSet 3");
            set3.setAxisDependency(YAxis.AxisDependency.RIGHT);
            set3.setColor(Color.YELLOW);
            set3.setCircleColor(Color.WHITE);
            set3.setLineWidth(2f);
            set3.setCircleRadius(3f);
            set3.setFillAlpha(65);
            set3.setFillColor(ColorTemplate.colorWithAlpha(Color.YELLOW, 200));
            set3.setDrawCircleHole(false);
            set3.setHighLightColor(Color.rgb(244, 117, 117));

            // create a data object with the data sets
            LineData data = new LineData(set1, set2, set3);
            data.setValueTextColor(Color.WHITE);
            data.setValueTextSize(9f);

            // set data
            chart.setData(data);
        }
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {
        chart.centerViewToAnimated(e.getX(), e.getY(), chart.getData().getDataSetByIndex(h.getDataSetIndex())
                .getAxisDependency(), 500);
    }

    @Override
    public void onNothingSelected() {

    }

    @Override
    public void onDestroyView() {
        handler.removeCallbacks(task);
        super.onDestroyView();
    }
}
